package com.oil.petro.eshop.controller;

import com.oil.petro.eshop.bean.BasicBean;
import com.oil.petro.eshop.bean.Page;
import com.oil.petro.eshop.bean.ProductBean;
import com.oil.petro.eshop.entity.Account;
import com.oil.petro.eshop.entity.Order;
import com.oil.petro.eshop.entity.Category;
import com.oil.petro.eshop.entity.Manufacturer;
import com.oil.petro.eshop.entity.Product;
import com.oil.petro.eshop.service.OrderService;
import com.oil.petro.eshop.service.CategoryService;
import com.oil.petro.eshop.service.ManufacturerService;
import com.oil.petro.eshop.service.ProductService;
import com.oil.petro.eshop.service.UserAccountService;
import com.oil.petro.eshop.utils.NavigationBar;
import com.oil.petro.eshop.utils.NavigationMenu;
import com.oil.petro.eshop.utils.PageStatus;
import com.oil.petro.eshop.utils.PaginationUtil;
import com.oil.petro.eshop.utils.Price;
import com.oil.petro.eshop.utils.ProductHelper;
import com.oil.petro.eshop.validator.ProductValidator;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.fileupload.DefaultFileItem;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ProductController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    ManufacturerService manufacturerService;

    @Autowired
    ProductService productService;

    @Autowired
    UserAccountService accountService;

    @Autowired
    OrderService orderService;

    private static final int PRODUCTS_AMOUNT = 8;
    PaginationUtil paginationUtil = new PaginationUtil();
    ProductHelper productHelper = new ProductHelper();
    NavigationBar bar = new NavigationBar();
    NavigationMenu menu = new NavigationMenu();

//     @Autowired
//  private ProductValidator productValidator;

//  
//  @InitBinder
//  protected void initBinder(WebDataBinder binder) {
//
//    binder.setValidator(productValidator);
//  }

    
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView showProductList(
            @RequestParam(value = "category", required = false) String categoryParam,
            @RequestParam(value = "manufacturer", required = false) String manufacturerParam,
            @RequestParam(value = "cost", required = false) String costParam,
            @RequestParam("page") int page, @ModelAttribute("commandBean") BasicBean basicBean,
            HttpServletRequest request) {

        List<Page> pageList;
        List<Product> productList;
        NavigationBar bar = new NavigationBar();
        NavigationMenu menu = new NavigationMenu();

        System.out.println("wchodzi" + basicBean.toString());

        if (categoryParam != null || manufacturerParam != null || costParam != null) {

            System.out.println("sa atrybuty" + basicBean.toString());

            productList = productService.searchProductList(basicBean, PRODUCTS_AMOUNT, page - 1);

            pageList = paginationUtil.getSearchPageList(basicBean, PRODUCTS_AMOUNT, page, 0, productService);

        } else {
            pageList = paginationUtil.getPageList(PRODUCTS_AMOUNT, page, productService);
            System.out.println("nie sa  " + page);
            productList = productService.getProductList(PRODUCTS_AMOUNT, page - 1);
            productList = productHelper.changeLengthProductDescription(productList);
        }

        Map<String, Object> model = new HashMap<>();
        boolean emptySearchResult = productList.isEmpty();
        model.put("emptySearchResult", emptySearchResult);
        model.put("productList", productList);
        model.put("pageList", pageList);

        if (request.getUserPrincipal() != null) {
            basicBean.setUser(request.getUserPrincipal().getName());
        } else {
            basicBean.setUser("");
        }
        bar.getNavigationBarDataModel(model, basicBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        //setDataModel(model, basicBean, emptySearchResult, PageStatus.ADMINISTRATOR.getValue());
        return new ModelAndView("product/productList", model);

    }

    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
    public ModelAndView executeSubmitOnProductListPage(@RequestParam("idf") int button, @RequestParam("page") int page,
            @ModelAttribute("commandBean") BasicBean basicBean, BindingResult result, SessionStatus status, HttpServletRequest request) {
        // Person person = new Person("Marcin", "Cichonski", "99-300", "Gandhiego", "Łódź");
        // Account account = new Account("login4", "password4", "email4", 1);
        //  PaginationUtil paginationUtil = new PaginationUtil();
        // List<Page> pageList = paginationUtil.getPageList(PRODUCTS_AMOUNT, page - 1, 0, productService);

        NavigationBar bar = new NavigationBar();
        NavigationMenu menu = new NavigationMenu();
        Map<String, Object> model = new HashMap<>();
        boolean emptySearchResult = true;
        if (basicBean.getCategory() != null || basicBean.getManufacturer() != null || basicBean.getCost() != null) {
            List<Product> productList = productService.searchProductList(basicBean, PRODUCTS_AMOUNT, page - 1);

            System.out.println("List sssssrrrr" + basicBean.getCost());
            model.put("productList", productList);
            List<Page> pageList = paginationUtil.getSearchPageList(basicBean, PRODUCTS_AMOUNT, page, 0, productService);
            model.put("pageList", pageList);
            emptySearchResult = productList.isEmpty();
        }

        //System.out.println("List rrrr");
        // List<Manufacturer> manufacturerList = manufacturerService.getManufacturerList();
        //List<Category> categoryList = categoryService.getCategoryList();
        // System.out.println("Basic2 " + basicBean.toString());
        // setDataModel(model, basicBean, emptySearchResult, PageStatus.LOGIN.getValue());
        model.put("emptySearchResult", emptySearchResult);
        if (request.getUserPrincipal() != null) {
            basicBean.setUser(request.getUserPrincipal().getName());
        } else {
            basicBean.setUser("");
        }
        bar.getNavigationBarDataModel(model, basicBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        // model.put("manufacturerList", manufacturerList);
        // model.put("categoryList", categoryList);
        // model.put("costList", Price.getPricePickerList());
        //  model.put("status", PageStatus.ADMINISTRATOR.getValue());//typ numeryczny to do
        // model.put("commandBean", basicBean);
        return new ModelAndView("product/productList", model);

    }

////     @RequestMapping(value = "/remind", method = RequestMethod.POST)
////    public String passwordRemiderSubmit(
////            @ModelAttribute("user") User user,
////            BindingResult result, SessionStatus status, HttpServletRequest request) {
////
////        reminder.validate(user, result);
////        if (result.hasErrors()) {
////            return "passwordReminder";
////        } else {
////            status.setComplete();
////            userManager.sendEmail(user.getEmail());
////            return "passwordReminder_step2";
////        }
////    }
//     @RequestMapping(value = "/list", method = RequestMethod.POST)
//    public ModelAndView executeSubmitOnProductListPage(@RequestParam("idf") int button, @ModelAttribute("commandBean") BasicBean basicBean, BindingResult result, SessionStatus status, HttpServletRequest request) {
//
//        List<Manufacturer> manufacturerList = manufacturerService.getManufacturerList();
//        List<Category> categoryList = categoryService.getCategoryList();
//         
//        Map<String, Object> model = new HashMap<String, Object>();
//        model.put("manufacturerList", manufacturerList);
//        model.put("categoryList", categoryList);
//        model.put("costList", Price.getPricePickerList());
//        model.put("status", PageStatus.ADMINISTRATOR.getValue());//typ numeryczny to do
//        model.put("commandBean", basicBean);
//
//        return new ModelAndView("product/productList", model);
//
//    }
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addProduct(Model model, HttpServletRequest request) {

        ProductBean productBean = new ProductBean();
        productBean.setUser(request.getUserPrincipal().getName());
        bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        return "product/productAdd";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String sumbitAddProduct(Model model,
            @ModelAttribute("commandBean") @Valid ProductBean productBean,
            BindingResult result, SessionStatus status, HttpServletRequest request) {

        productBean.setUser(request.getUserPrincipal().getName());
        bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        System.out.println("ProducBean " + productBean.toString());
        if (result.hasErrors()) {
            System.out.println("Validacja");
            return "product/productAdd";
        }

        Product product = productHelper.prepareNewProdcutToSave(productBean, categoryService, manufacturerService);
        int id = productService.saveProduct(product);

        return "redirect:details.htm?id=" + id;
    }

    // ok
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public ModelAndView deleteProduct(@ModelAttribute("commandBean") ProductBean productBean,
            @RequestParam(value = "id", required = false) Integer productId,
            @RequestParam(value = "page", required = false) Integer page,
            HttpServletRequest request) {

        Map<String, Object> model = new HashMap<>();

        if (productId != null) {
            productService.deleteProduct(productId);
        }

        productBean.setUser(request.getUserPrincipal().getName());

        List<Product> productList = productService.getProductList(PRODUCTS_AMOUNT, page - 1);
        List<ProductBean> productBeanList = productHelper.getProductListForEditDelete(productList);
        List<Page> pageList = paginationUtil.getPageList("delete", PRODUCTS_AMOUNT, page, productService);

        boolean emptySearchResult = productList.isEmpty();

        model.put("emptySearchResult", emptySearchResult);
        model.put("productList", productBeanList);
        model.put("pageList", pageList);

        // NavigationBar bar = new NavigationBar();
        // NavigationMenu menu = new NavigationMenu();
        bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        return new ModelAndView("product/productDeleteList", model);
    }

//ok
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView editProduct(@ModelAttribute("commandBean") ProductBean productBean,
            @RequestParam(value = "id", required = false) Integer productId,
            @RequestParam(value = "page", required = false) Integer page,
            HttpServletRequest request) {

        Map<String, Object> model = new HashMap<>();
        productBean.setUser(request.getUserPrincipal().getName());
        bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        if (productId != null) {
            Product product = productService.getProduct(productId);
            productBean = productHelper.prepareProductToDisplayDetails(product, categoryService, manufacturerService);
            productBean.setId(productId);
            model.put("commandBean", productBean);
            return new ModelAndView("product/productEdit", model);
        }

        List<Product> productList = productService.getProductList(PRODUCTS_AMOUNT, page - 1);
        List<ProductBean> productBeanList = productHelper.getProductListForEditDelete(productList);
        List<Page> pageList = paginationUtil.getPageList("edit", PRODUCTS_AMOUNT, page, productService);

        boolean emptySearchResult = productList.isEmpty();

        model.put("emptySearchResult", emptySearchResult);
        model.put("productList", productBeanList);
        model.put("pageList", pageList);

        //  NavigationBar bar = new NavigationBar();
        //NavigationMenu menu = new NavigationMenu();
        return new ModelAndView("product/productEditList", model);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String sumbitEditProduct(Model model,
            @ModelAttribute("commandBean") @Valid ProductBean productBean,
            BindingResult result, SessionStatus status, HttpServletRequest request) {

        productBean.setUser(request.getUserPrincipal().getName());
        bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);

        if (result.hasErrors()) {
            System.out.println("Validacja");
            return "product/productEdit";
        }

        Product product = productHelper.prepareProdcutToUpdate(productBean, categoryService, manufacturerService, productService);
        productService.updateProduct(product);

        return "redirect:details.htm?id=" + productBean.getId();
    }

    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public ModelAndView detailsProduct(@RequestParam("id") int id, HttpServletRequest request,
            @RequestParam(value = "error", required = false) Integer error) {

        ProductHelper productHelper = new ProductHelper();
        Product product = productService.getProduct(id);
        ProductBean productBean = productHelper.prepareProductToDisplayDetails(product, categoryService, manufacturerService);
        Map<String, Object> model = new HashMap<String, Object>();

        System.out.println("aaaaaaaaaa11");
        if (error != null) {
            System.out.println("aaaaaaaaaa1");
            if (error == 1) {
                // String msg = "Niewystarczjąca ilość dostepnego towaru";
                System.out.println("aaaaaaaaaa2");
                model.put("error", 1);
            } else if (error == 2) {
                System.out.println("aaaaaaaaaa3");
                //String msg = "Nieprawidłowy typ danych. Wymagana wartość liczbowa";
                model.put("error", 2);

            }

        }
        System.out.println("aaaaaaaaaa4");
        NavigationBar bar = new NavigationBar();
        NavigationMenu menu = new NavigationMenu();
        if (request.getUserPrincipal() != null) {
            productBean.setUser(request.getUserPrincipal().getName());
            productBean.setId(id);
        } else {
            productBean.setUser("");
        }
        bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);
        System.out.println("aaaaaaaaaa5");
        return new ModelAndView("product/productDetails", model);
    }

    @RequestMapping(value = "/details", method = RequestMethod.POST)
    public String buyProduct(Model model, @ModelAttribute("commandBean") @Valid ProductBean productBean,
            BindingResult result,
            @RequestParam("id") int id,
            HttpServletRequest request ) {

        System.out.println("ASccount");

        ProductHelper productHelper = new ProductHelper();
        productBean.setUser(request.getUserPrincipal().getName());

        Product product = productService.getProduct(id);
        Account account = accountService.getAccountByLogin(productBean.getUser());
        
         productBean.setUser(request.getUserPrincipal().getName());
         bar.getNavigationBarDataModel(model, productBean, accountService);
        menu.getNavigationMenuDataModel(model, categoryService, manufacturerService);
        
        
       ProductValidator validator = new ProductValidator();
                
        
        if (validator.hasErrors(productBean)) {
            System.out.println("Validacja");
          return "redirect:details.htm?id=" + id + "&error=2";
        }
        
        if (!productService.updateProduct(productBean, product)) {

            return "redirect:details.htm?id=" + id + "&error=1";
        }

        System.out.println("ASccount" + account.getId() + "p" + product.getId());
        Order order = new Order(account.getId(), product.getId(), Integer.parseInt(productBean.getOrderedQuantity()));
        if (orderService.isEmpty(account.getId(), product.getId())) {

            orderService.saveOrder(order);
        } else {
            order = orderService.getOrder(account.getId(), product.getId());
            order.setOrderedQuantity(order.getOrderedQuantity() + Integer.parseInt(productBean.getOrderedQuantity()));
            orderService.updateOrder(order);

        }
        return "redirect:cart.htm?step=1";
    }

}
